#!/usr/bin/env python3

import os
import socket
import time
import threading

class P2pWebServer:
    def __init__(self):
        self.WebHost = 'www.xxx.cn' # 引导服务器地址
        self.Port = 50010
        self.listen_port = 50007
        self.WaitObj = threading.Event()

    def run(self):
        self.ConnPairThread = threading.Thread(target=self.ConnectToPair)
        self.ConnPairThread.start()
        self.ConnectWebServer()

    def ConnectToPair(self):
        while True:
            self.WaitObj.wait()
            pair_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            pair_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            pair_tcp.bind(('0.0.0.0', self.listen_port))
            pair_tcp.listen(1)
            conn, addr = pair_tcp.accept()
            print('connect by', addr)
            data = conn.recv(1024)
            print(data)
            pair_tcp.close()

    def ConnectWebServer(self):
        tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        tcp.connect((self.WebHost, self.Port))
        while True:
            tcp.send(("RegisterIp:"+str(self.listen_port)).encode())
            data = tcp.recv(1024)
            if data:
                if data == "NoReq":
                    continue
                else:
                    data = data.decode()
                    gateway_ip, gateway_port = data.split(":")
                    print(gateway_ip, gateway_port)
                    self.WaitObj.set()
                    time.sleep(10)
                    


if __name__ == '__main__':
    s = P2pWebServer() 
    s.run()
